﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ZX.Web.UI.Controls
{


    public class DeptTree : Literal
    {
        private string _tableName = "";
        [Description("数据来源的表名")]
        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }

        private string _caption = "";
        [Description("文本")]
        public string Caption
        {
            get { return _caption; }
            set { _caption = value; }
        }
        private string _key = "";
        [Description("主键")]
        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }
        private string _parentKey = "";
        [Description("父节点主键")]
        public string ParentKey
        {
            get { return _parentKey; }
            set { _parentKey = value; }
        }
        private string _path = "";
        [Description("节点路径")]
         public string path
        {
            get { return _path; }
            set { _path = value; }
        }
        private bool _isAllowCheck = false;
        [Description("是否允许多选")]
        public bool AllowCheck
        {
            get { return _isAllowCheck; }
            set { _isAllowCheck = value; }
        }
        private int _IsOutDepartment = 0;
        [Description("组织架构类型")]
        public int IsOutDepartment
        {
            get { return _IsOutDepartment; }
            set { _IsOutDepartment = value; }
        }
        private Guid _userID = Guid.Empty;
        [Description("外部人员ID")]
        public Guid userID
        {
            get { return _userID; }
            set { _userID = value; }
        }
        private int _IsVirtual=0;
        [Description("是否虚拟部门")]
        public int IsVirtual
        {
            get { return _IsVirtual; }
            set { _IsVirtual = value; }
        }
        private string _Condition = "";
        [Description("自定义查询条件")]
        public string Condition
        {
            get { return _Condition; }
            set { _Condition = value; }
        }

        /// <summary>
        /// 实体类
        /// </summary>
        public string Entity
        {
            get
            {
               return  ParentPage.GetStringFromQueryString("entity","");
            }
        }


        public Guid FunctionID
        {
            get
            {
                return ParentPage.GetGuidFromQueryString("functionid");
            }
        }

        public BasePage ParentPage
        {

            get
            {
                return this.Page as BasePage;
            }
        }

        private string createTree(string DeptPath, IList<TreeViewData> list)
        {
            StringBuilder _strHtml = new StringBuilder();
            string sql = "";
            if (AllowCheck)
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg ygtv-checkbox'>");
            else
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg'>");
            _strHtml.Append("<ul>");
            // 得到一级菜单
            // IList<TreeViewData> rootlist = list.Where(p => p.Path.Split('-').Length == 2).OrderBy(p => p.Path).ToList();
            IList<TreeViewData> rootlist = null;
            // 判断是否是外部机构的用户
            // sql="select * from datdepartment where deptid in (select deptid from TrCustomer where  TrCustomerID='"+userID+"')";
            //
            rootlist = list.Where(p => p.Path == DeptPath).OrderBy(p => p.Path).ToList();
            int i = 0;
            if (rootlist != null)
            {
                foreach (TreeViewData tree in rootlist)
                {

                    _strHtml.Append("<li>");
                    if (!AllowCheck)
                    {
                        _strHtml.Append("<span><a href=\"#" + tree.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + tree.Caption + "','" + tree.Key + "','" + tree.DeptType + "')\">" + tree.Caption + "</a></span>");
                    }
                    else
                    {
                        _strHtml.Append("<a href='#@" + tree.Key + "'>" + tree.Caption + "</a>");
                    }

                    //功能明细
                    AddNode(list, tree.Key, _strHtml);
                    _strHtml.Append("</li>");
                    i++;
                }
            }
            else
            {
                _strHtml.Append("<li>权限不足或数据不存在</li>");
            }
            _strHtml.Append("</ul>");
            _strHtml.Append("</div>");
            return _strHtml.ToString();
        }
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            StringBuilder sbChilds=new StringBuilder();
            if (!DesignMode )
            {
                string sql = "select DeptID as [key],dept.DeptName as Caption,b.deptname as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from DatDepartment dept,dbo.fn_GetOrganizeAll('333FE8ED-CA2A-497A-A88C-3BB4FB3A1A57') b where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and dept.DeptID=b.id";
                sql = string.Format(sql, DateTime.Now.ToLongTimeString());

                IList<TreeViewData> list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
                string deptPath = "@001";
                if ((this.Entity.IndexOf("Employee")>0 || this.Entity.IndexOf("Department") > 0) && this.FunctionID != Guid.Empty)
                {
                    var _DeptID = ParentPage.EmpPropertyValues.DeptID;
                    var dept = list.Where(p => p.Key.ToString() == _DeptID).First();
                    if (dept.LCaption.IndexOf("学校") > 0 || dept.LCaption.IndexOf("分公司") > 0 || dept.LCaption.IndexOf("推广中心") > 0)
                    {
                        string[] _strDept = dept.LCaption.Replace("->","_").Split('_');
                        string[] _strPath = dept.Path.Replace("->","_").Split('-');
                        for (int i = 0; i < _strDept.Length;i++ )
                        {
                            if (_strDept[i].IndexOf("分公司") >= 0 || _strDept[i].IndexOf("推广中心") >= 0 || _strDept[i].IndexOf("学校") >= 0)
                            {
                                deptPath +="-"+ _strPath[i];
                                break;
                            }
                            if(i>0){
                                deptPath +="-"+ _strPath[i];
                            }
                        }
                    }
                }
                //(this.Page as BasePage).EmpPropertyValues.DeptID
                writer.Write(createTree(deptPath,list));
                base.Render(writer);
            }
            else
            {
                writer.Write("树型菜单");
            }
        }
        private void AddNode(IList<TreeViewData> list, Guid? key,StringBuilder sb)
        {
            var detail = list.Where(p => p.ParentKey==key).OrderBy(p => p.Path).ToList();
            if (detail.ToList().Count > 0)
            {
                sb.Append("<ul>");
                foreach (TreeViewData v in detail)
                {
                    sb.Append("<li>");
                    if (!AllowCheck)
                    {
                        sb.Append("<span><a href=\"#" + v.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + v.Caption + "','" + v.Key + "','" + v.DeptType + "')\">" + v.Caption + "</a></span>");
                    }
                    else
                    {
                        sb.Append("<a href='#@" + v.Key + "'>" + v.Caption + "</a>");
                    }
                    AddNode(list, v.Key, sb);
                    sb.Append("</li>");

                }
                sb.Append("</ul>");
            }
            //childName += "</ul>";
          
         
        }

   
    }
}
